package com.every.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Map;

/**
 * @description: http请求工具类
 * @author: yh
 * @date: 2022/11/2
 */
@Component
public class RequestUtil {
    private static RestTemplate restTemplate;

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        RequestUtil.restTemplate = restTemplate;
    }

    // 今日图片信息接口
    public final static String TODAY_IMAGE_URL = "https://api.xygeng.cn/bing";
    // 万年历接口
    public final static String PERPETUAL_CALENDAR_URL = "https://api.xygeng.cn/day";
    // 随机生成一句话接口
    public final static String NEW_TEXT_URL = "https://api.xygeng.cn/one";
    // 微博热搜
    public final static String WEIBO_URL = "https://www.coderutil.com/api/resou/v1/weibo";
    // 知乎热搜
    public final static String ZHIHU_URL = "https://www.coderutil.com/api/resou/v1/zhihu";
    // 今日歌曲
    public final static String MUSIC_RECOMMEND_URL = "https://www.coderutil.com/api/music/v1/recommend";
    // 历史上的今天
    public final static String RESOU_TODAY_URL = "https://www.coderutil.com/api/resou/v1/today";
    // 百度热搜
    public final static String BAIDU_URL = "https://www.coderutil.com/api/resou/v1/baidu";

    /**
     * 发送post请求
     *
     * @param url
     * @param request
     * @author: yh
     * @date: 2022/11/2
     */
    public static JSONObject postForObject(String url, Object request) {
        return restTemplate.postForObject(url, request, JSONObject.class);
    }

    /**
     * 发送get请求
     *
     * @param url     请求地址
     * @param headers 请求头
     * @author: yh
     * @date: 2022/11/2
     */
    public static JSONObject getForObject(String url, HttpHeaders headers) {
        //请求头
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("accessToken", "3d40e41e9d764d30a9a4d72e61ad61b9");
        //封装请求头
        HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<MultiValueMap<String, Object>>(headers);
        ResponseEntity<String> result4 = restTemplate.exchange(url, HttpMethod.GET, formEntity, String.class);
        String body = result4.getBody();
        return JSONObject.parseObject(body);
    }

    public static JSONObject getForObject(String url) {
        //请求头
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("accessToken", "3d40e41e9d764d30a9a4d72e61ad61b9");
        //封装请求头
        ResponseEntity<String> result4 = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        String body = result4.getBody();
        return JSONObject.parseObject(body);
    }

    /**
     * 发送get请求
     *
     * @param url     请求地址
     * @param headers 请求头
     * @param param   参数
     * @author: yh
     * @date: 2022/11/2
     */
    public static JSONObject getForObject(String url, HttpHeaders headers, Map<String, String> param) {
        HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<MultiValueMap<String, Object>>(headers);
        if (!CollectionUtils.isEmpty(param)) {
            ArrayList<String> paramList = new ArrayList<>(param.keySet());
            for (int i = 0; i < paramList.size(); i++) {
                String key = paramList.get(i);
                if (i == 0) {
                    url += "?";
                } else {
                    url += "&";
                }
                url += key + "=" + param.get(key);
            }
        }
        ResponseEntity<String> result4 = restTemplate.exchange(url, HttpMethod.GET, formEntity, String.class);
        String body = result4.getBody();
        return JSONObject.parseObject(body);
    }

    /**
     * 返回字符串
     *
     * @param url
     * @author: yh
     * @date: 2022/11/11
     */
    public static String getForStr(String url) {
        return restTemplate.getForObject(url, String.class);
    }

    /**
     * get请求，处理url中有特殊字符的路径
     *
     * @param url1 请求路径
     * @author: yh
     * @date: 2022/11/11
     */
    public static JSONObject getEncodeFor(String url1) {
        //链接
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuffer result = new StringBuffer();
        try {
            //创建连接
            URL url = new URL(url1);
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //设置连接超时时间
            connection.setConnectTimeout(15000);
            //设置读取超时时间
            connection.setReadTimeout(15000);
            //开始连接
            connection.connect();
            //获取响应数据
            if (connection.getResponseCode() == 200) {
                //获取返回的数据
                is = connection.getInputStream();
                if (is != null) {
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String temp = null;
                    while ((temp = br.readLine()) != null) {
                        result.append(temp);
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();// 关闭远程连接
        }
        return JSONObject.parseObject(result.toString());
    }
}
